from django.views.generic import ListView, DetailView
from blog.models import Post, PostUserData, UserNotification
from blog.forms import NotificationsForm
from django.contrib.comments import Comment
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required


class PostDetailView(DetailView):
    model=Post
    context_object_name = 'post'
    template_name = 'post.html'

    def get_context_data(self, **kwargs):
        user = self.request.user
        post = self.object
        count = self.object.postmeta.comments_count
        if user.is_authenticated():
            puds = PostUserData.objects.filter(
                user__id__exact=user.id
            ).filter(
                post__id__exact=post.id
            )
            if puds:
                pud = puds[0]
                if pud.read != count:
                    pud.read = count
                    pud.save()
            else:
                PostUserData.objects.create(
                    user = user,
                    post = post,
                    read = count
                    )
        return super(PostDetailView, self).get_context_data(**kwargs)



class PostListView(ListView):
    model=Post
    template_name='posts.html'
    context_object_name='posts'
    paginate_by=10

    def get_context_data(self, **kwargs):
        user = self.request.user
        queryset = kwargs.get('object_list')
        if user.is_authenticated():
            for post in queryset:
                puds = PostUserData.objects.filter(
                    user__id__exact=user.id
                ).filter(
                    post__id__exact=post.id
                )
                if puds:
                    pud = puds[0]
                    new_count = post.postmeta.comments_count
                    if pud.read < new_count:
                        post.diff_count = new_count - pud.read
        context = super(PostListView, self).get_context_data(**kwargs)
        context['object_list'] = queryset
        context[self.context_object_name] = queryset
        return context



class CommentDetailView(DetailView):
    model=Comment
    context_object_name = 'post'
    template_name = 'show_comment.html'



@login_required
def notification_manager(request):
    notifications = UserNotification.objects.get(user=request.user.id)
    if request.method == 'POST':
        form = NotificationsForm(request.POST, instance=notifications)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('notification_manager'))
    else:
        form = NotificationsForm(instance=notifications)
    return render(request, 'notification_manager.html', {'form': form})


